package com.gxa.common.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 文件上传、下载工具类
 */
public class FileUtils {

    /**
     * 上传文件
     *
     * @param path    文件的相对路径
     * @param file    上传文件数据
     * @param request 请求
     * @return 文件的绝对路径
     */
    public static String fileUpload(String path, MultipartFile file, HttpServletRequest request)  {
        //1.获取文件要保存的真实路径
        System.out.println(request.getServletContext());
        String realPath = request.getServletContext().getRealPath(path);
        //2.创建上传文件的路径
        File filePath = new File(realPath);
        if(!filePath.exists())
            filePath.mkdirs();
        //3.更改文件名称，避免冲突
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename=UUID.randomUUID().toString()+suffix;
        //4.保存文件到服务器
        File uploadfile = new File(filePath, newFilename);
        try {
            file.transferTo(uploadfile);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传出现问题");
        }
        //5.返回服务器的绝对路径

        return uploadfile.getPath();

        //6.返回服务器相对路径
        /*String relativePath = path + "/" +newFilename;
        return relativePath;*/
    }

    /**
     * 下载文件
     *
     * @param path    文件的相对路径
     * @param fileName 文件名
     * @param request 请求
     * @param response 响应
     *
     */
    public static void fileDownLoad(String path, String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1.获取文件的真实路径
        String realPath = request.getServletContext().getRealPath(path) + "\\" + fileName;
        //2.设置response响应头
        response.reset(); //设置页面不缓存,清空buffer
        response.setCharacterEncoding("UTF-8"); //字符编码
        response.setContentType("multipart/form-data"); //二进制传输数据
        response.setHeader("Content-Disposition",////设置文件下载头
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        //3.创建缓存文件输入流
        InputStream input = new BufferedInputStream(new FileInputStream(new File(realPath)));
        //4.创建缓存文件输出流
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        //5.下载文件
        byte[] buff = new byte[1024];
        int index = 0;
        while ((index = input.read(buff)) != -1) {
            out.write(buff, 0, index);
            out.flush();
        }
        out.close();
        input.close();

    }
}

